package com.leyou.user.controller;

import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import java.util.stream.Collectors;

@RestController
@RequestMapping("info")
public class UserController {
    @Autowired
    private UserService userService;

    /*
    * 查询用户信息是否存在
    * */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> existsData(@PathVariable("data") String data,
                                              @PathVariable("type")  Integer type){

        return ResponseEntity.ok(userService.existsData(data, type));

    }
    /*
    * 用户注册验证码发送
    * */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam String phone){

        userService.sendCode(phone);
//        验证码发送返回204
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

        /*
        * 用户注册
        * */
     @PostMapping
    public ResponseEntity<Void> register(User user , BindingResult result,
                                         @PathVariable("code") String code){

         if (result.hasErrors()) {
             String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                     .collect(Collectors.joining("|"));
             throw new LyException(400, msg);
         }


         userService.register(user, code);
//         用户注册成功
         return ResponseEntity.status(HttpStatus.CREATED).build();

        }

        /*
        * 根据手机号和密码查询用户信息
        * */
        @GetMapping
    public ResponseEntity<UserDTO> queryUserByPhoneAndPassword(
            @RequestParam("username") String username, @RequestParam("password") String password
        ){
            return ResponseEntity.ok(userService.queryUserByPhoneAndPasssword(username, password));
        }
        /*
        * 获取当前用户信息
        * */
        @GetMapping("me")
    public ResponseEntity<UserDetails> getMe(){
            return ResponseEntity.ok(UserContext.getUser());
        }

}
